package cn.com.system.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.common.config.FileUploadProperties;
import cn.com.common.exception.BusinessException;
import cn.com.common.result.DataResult;
import cn.com.system.entity.SysFilesEntity;
import cn.com.system.mapper.SysFilesMapper;
import cn.com.system.service.SysFilesService;
import cn.com.util.DateUtils;

/**
 * 文件上传 服务类
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@EnableConfigurationProperties(FileUploadProperties.class)
@Service("sysFilesService")
public class SysFilesServiceImpl extends ServiceImpl<SysFilesMapper, SysFilesEntity> implements SysFilesService {
	@Resource
	private FileUploadProperties fileUploadProperties;

	@Resource
	private HttpSessionService httpSessionService;

	@Resource
	private SysFilesMapper sysFilesMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.easytax.service.SysFilesService#saveFile(org.springframework.web.
	 * multipart.MultipartFile)
	 */
	@Transactional
	@Override
	public DataResult saveFile(MultipartFile[] files) {
		// 存储文件夹
		String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
		String newPath = fileUploadProperties.getPath() + createTime + File.separator;
		File uploadDirectory = new File(newPath);
		if (uploadDirectory.exists()) {
			if (!uploadDirectory.isDirectory()) {
				uploadDirectory.delete();
			}
		} else {
			uploadDirectory.mkdir();
		}

		try {
			List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
			for (MultipartFile file : files) {
				String fileName = file.getOriginalFilename();
				// id与filename保持一直，删除文件
				String fileNameNew = UUID.randomUUID().toString().replace("-", "") + getFileType(fileName);
				// 作为录音文件上传的blob，在后面增加.wav后缀
				if (fileName.equals("blob")) {
					fileNameNew = fileNameNew + ".wav";
				}
				String newFilePathName = newPath + fileNameNew;

				String url = fileUploadProperties.getUrl() + "/" + createTime + "/" + fileNameNew;
				// 创建输出文件对象
				File outFile = new File(newFilePathName);
				// 拷贝文件到输出文件对象
				FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
				// 保存文件记录
				SysFilesEntity sysFilesEntity = new SysFilesEntity();

				sysFilesEntity.setFileName(fileName);
				sysFilesEntity.setFilePath(newFilePathName);
				sysFilesEntity.setUrl(url);
				this.save(sysFilesEntity);
				
				Map<String, String> resultMap = new HashMap<>();
				resultMap.put("src", url);
				listMap.add(resultMap);
			}
			return DataResult.success(listMap);
		} catch (Exception e) {
			throw new BusinessException("上传文件失败");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.easytax.service.SysFilesService#removeByIdsAndFiles(java.util.
	 * List)
	 */
	@Transactional
	@Override
	public void removeByIdsAndFiles(List<String> ids) {
		List<SysFilesEntity> list = this.listByIds(ids);
		list.forEach(entity -> {
			// 如果之前的文件存在，删除
			File file = new File(entity.getFilePath());
			if (file.exists()) {
				file.delete();
			}
		});
		this.removeByIds(ids);

	}

	/**
	 * 获取文件后缀名
	 *
	 * @param fileName
	 *            文件名
	 * @return 后缀名
	 */
	private String getFileType(String fileName) {
		if (fileName != null && fileName.contains(".")) {
			return fileName.substring(fileName.lastIndexOf("."));
		}
		return "";
	}

}